<template>
  <!-- 登录页面 -->
  <div>
    <Row class="container">
      <i-col span="13" offset="2" class="login-img-box">
        <img src="/img/sale.jpg" alt="" />
      </i-col>
      <i-col span="7" class="login-box">
        <div class="login-container">
          <div class="login-header">
            <p>欢迎登录</p>
          </div>
          <div class="form-box">
            <Form ref="formInline" :model="formDate" :rules="ruleInline">
              <FormItem prop="username">
                <i-input
                  type="text"
                  v-model="formDate.username"
                  clearable
                  size="large"
                  placeholder="用户名"
                >
                  <Icon type="person" slot="prepend"></Icon>
                </i-input>
              </FormItem>
              <FormItem prop="password">
                <i-input
                  type="password"
                  v-model="formDate.password"
                  clearable
                  size="large"
                  placeholder="密码"
                >
                  <Icon type="ios-locked-outline" slot="prepend"> </Icon>
                </i-input>
              </FormItem>
              <FormItem prop="imageCode">
                <i-input
                  type="text"
                  v-model="formDate.imageCode"
                  clearable
                  size="large"
                  placeholder="验证码"
                  style="width: 50%"
                >
                  <Icon type="ios-compose-outline" slot="prepend"> </Icon>
                </i-input>
                <img
                  :src="imageUrl"
                  alt="验证码未出现"
                  style="
                    width: 50%;
                    position: absolute;
                    top: 0px;
                    left: 50%;
                    height: 100%;
                  "
                  @click="getImageThrottle"
                />
              </FormItem>

              <!-- 验证码结束 -->
              <FormItem>
                <Button
                  type="error"
                  size="large"
                  @click="handleSubmit('formInline')"
                  long
                  >登录</Button
                >
              </FormItem>
            </Form>
          </div>
        </div>
      </i-col>
    </Row>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { validUsername } from '~/utils/validate'
import { addTempCartToCart } from '~/api/cart'
import { getImage } from '~/api/user'
import Cookies from 'js-cookie'

export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('账户名由5~12位字母数字汉字组成，请检查'))
      } else {
        callback()
      }
    }
    const validateImageCode = (rule, value, callback) => {
      if (value.length !== 4) {
        callback(new Error('请输入四位验证码'))
      } else {
        callback()
      }
    }

    return {
      // 节流定时器
      previous: 0,
      isShow: false,
      imageUrl: '',
      // 表单
      formDate: {
        username: '',
        password: '',
        imageCode: ''
      },
      // 用户名与密码的校验规则
      ruleInline: {
        username: [
          { required: true, trigger: 'blur', validator: validateUsername }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { type: 'string', min: 6, message: '密码不少于6位，请检查', trigger: 'blur' }
        ],
        imageCode: [
          { required: true, trigger: 'blur', validator: validateImageCode }
        ]
      }
    }
  },
  created() {
    this.getImage()
  },
  methods: {
    ...mapActions('user', ['login']),
    ...mapActions('cart', ['loadShoppingCart']),
    getImage() {
      getImage().then((res) => {
        this.imageUrl = res.data
      })
    },
    // 图形验证码节流
    getImageThrottle() {
      const now = new Date().getTime()
      if (this.previous + 1000 <= now) {
        this.previous = now
        this.getImage()
      }
    },
    handleSubmit(name) {
      const father = this
      // eslint-disable-next-line space-before-function-paren
      this.$refs[name].validate(async (valid) => {
        if (valid) {
          // 加密密码
          const password = await father.$encrypt(father.formDate.password)
          this.login({
            username: father.formDate.username,
            password,
            imageCode: father.formDate.imageCode
          }).then(result => {
            if (result === 'success') {
              this.$Message.success('登录成功')
              // 判断是否有临时购物车，有且内有数据的话进行添加操作
              let tempData = []
              if (Cookies.get('tempCarts')) {
                tempData = JSON.parse(Cookies.get('tempCarts'))
              }
              if (tempData.length > 0) {
                const uid = this.$store.state.user.userInfo.uid
                // 将临时购物车添加进用户的购物车，发出http请求，此处不用等待结果，跳回首页
                addTempCartToCart(uid, tempData).then((res) => {
                  // 请求成功清除临时购物车
                  if (res.code === 200) {
                    this.$store.commit('cart/SET_TEMP_SHOPPING_CART', [])
                  } else {
                    // 失败了，也不做保存
                    this.$store.commit('cart/SET_TEMP_SHOPPING_CART', [])
                    this.$Message.error('临时购物车添加失败')
                  }
                })
              }
              father.$router.push('/')
            } else {
              this.getImage()
              this.$Message.error('用户名或密码错误')
            }
          })
        } else {
          this.$Message.error('请检查登录信息')
        }
      })
    }

  }
}
</script>

<style scoped>
.container {
  margin-top: 30px;
  height: 485px;
  background-color: #fff;
}
.login-img-box {
  height: 485px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}
.login-img-box > img {
  width: 68%;
}
.login-box {
  height: 485px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.login-container {
  width: 80%;
  height: 320px;
  border: #ed3f14 solid 1px;
}
.login-header {
  height: 50px;
  font-size: 20px;
  text-align: center;
  line-height: 50px;
  letter-spacing: 5px;
  color: #fff;
  background-color: #ed3f14;
}
.form-box {
  width: 80%;
  margin: 30px auto;
}
</style>
